<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>活动报名管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #4361ee;
            --success-color: #4cc9f0;
            --warning-color: #f72585;
            --danger-color: #e63946;
        }

        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .header {
            background: linear-gradient(135deg, var(--primary-color), #3a0ca3);
            color: white;
            padding: 1rem 0;
            margin-bottom: 2rem;
        }

        .card {
            border-radius: 15px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            border: none;
            margin-bottom: 1.5rem;
            transition: transform 0.3s ease;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        .card-header {
            background: transparent;
            border-bottom: 1px solid rgba(0,0,0,0.05);
            font-weight: 600;
            padding: 1.25rem 1.5rem;
        }

        .status-badge {
            padding: 0.5em 0.75em;
            border-radius: 20px;
            font-size: 0.85em;
            font-weight: 500;
        }

        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }

        .status-approved {
            background-color: #d4edda;
            color: #155724;
        }

        .status-rejected {
            background-color: #f8d7da;
            color: #721c24;
        }

        .status-cancelled {
            background-color: #e2e3e5;
            color: #383d41;
        }

        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .btn-success {
            background-color: var(--success-color);
            border-color: var(--success-color);
        }

        .action-btn {
            margin: 0 2px;
        }

        .search-box {
            background: white;
            border-radius: 30px;
            padding: 0.5rem 1rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .table th {
            font-weight: 600;
        }

        .table-hover tbody tr:hover {
            background-color: rgba(67, 97, 238, 0.05);
        }

        .modal-content {
            border-radius: 15px;
            border: none;
        }

        .form-control, .form-select {
            border-radius: 10px;
            padding: 0.75rem;
        }

        .toast-container {
            z-index: 1050;
        }
    </style>
</head>
<body>
<!-- 头部 -->
<div class="header text-center">
    <div class="container">
        <h1><i class="bi bi-people-fill"></i> 活动报名管理系统</h1>
        <p class="lead">管理志愿者活动报名信息</p>
    </div>
</div>

<div class="container">
    <!-- 搜索和操作区域 -->
    <div class="row mb-4">
        <div class="col-md-8">
            <div class="search-box d-flex align-items-center">
                <i class="bi bi-search me-2 text-muted"></i>
                <input type="text" class="form-control border-0" placeholder="搜索活动或用户..." id="searchInput">
            </div>
        </div>
        <div class="col-md-4 text-end">
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#enrollModal">
                <i class="bi bi-plus-circle"></i> 新增报名
            </button>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-muted">总报名数</h5>
                    <h2 class="text-primary">128</h2>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-muted">待审核</h5>
                    <h2 class="text-warning">24</h2>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-muted">已通过</h5>
                    <h2 class="text-success">89</h2>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-muted">已拒绝</h5>
                    <h2 class="text-danger">15</h2>
                </div>
            </div>
        </div>
    </div>

    <!-- 报名列表 -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span><i class="bi bi-list-check"></i> 报名记录列表</span>
            <div>
                <select class="form-select form-select-sm d-inline-block w-auto" id="statusFilter">
                    <option value="">全部状态</option>
                    <option value="0">待审核</option>
                    <option value="1">已通过</option>
                    <option value="2">已拒绝</option>
                    <option value="3">已取消</option>
                </select>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>活动ID</th>
                        <th>用户ID</th>
                        <th>报名时间</th>
                        <th>状态</th>
                        <th>审核人</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="enrollTableBody">
                    <!-- 数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>

            <!-- 分页 -->
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center">
                    <li class="page-item disabled"><a class="page-link" href="#">上一页</a></li>
                    <li class="page-item active"><a class="page-link" href="#">1</a></li>
                    <li class="page-item"><a class="page-link" href="#">2</a></li>
                    <li class="page-item"><a class="page-link" href="#">3</a></li>
                    <li class="page-item"><a class="page-link" href="#">下一页</a></li>
                </ul>
            </nav>
        </div>
    </div>
</div>

<!-- 新增/编辑报名模态框 -->
<div class="modal fade" id="enrollModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="enrollModalLabel"><i class="bi bi-person-plus"></i> 报名信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="enrollForm">
                    <input type="hidden" id="enroll_id">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="activity_id" class="form-label">活动ID</label>
                            <input type="number" class="form-control" id="activity_id" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="user_id" class="form-label">用户ID</label>
                            <input type="number" class="form-control" id="user_id" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="enroll_status" class="form-label">报名状态</label>
                            <select class="form-select" id="enroll_status" required>
                                <option value="0">待审核</option>
                                <option value="1">已通过</option>
                                <option value="2">已拒绝</option>
                                <option value="3">已取消</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="check_user_id" class="form-label">审核人ID</label>
                            <input type="number" class="form-control" id="check_user_id">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="check_remark" class="form-label">审核备注</label>
                        <textarea class="form-control" id="check_remark" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveEnrollBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- Toast提示 -->
<div class="toast-container position-fixed bottom-0 end-0 p-3">
    <div id="toast" class="toast" role="alert">
        <div class="toast-header">
            <strong class="me-auto">提示</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body" id="toastMessage"></div>
    </div>
</div>

<!-- JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<script>
    // API基础URL
    const API_BASE = 'http://localhost:8181/api/enroll';

    // 状态映射
    const statusMap = {
        0: { text: '待审核', class: 'status-pending' },
        1: { text: '已通过', class: 'status-approved' },
        2: { text: '已拒绝', class: 'status-rejected' },
        3: { text: '已取消', class: 'status-cancelled' }
    };

    // 初始化页面
    document.addEventListener('DOMContentLoaded', function() {
        console.log('🚀 页面加载完成，开始初始化...');
        loadEnrollData();

        // 绑定事件
        document.getElementById('saveEnrollBtn').addEventListener('click', saveEnroll);
        document.getElementById('statusFilter').addEventListener('change', loadEnrollData);
    });

    // 加载报名数据
    function loadEnrollData() {
        const status = document.getElementById('statusFilter').value;
        let url = `${API_BASE}/list`;

        if (status !== '') {
            url = `${API_BASE}/list/status/${status}`;
        }

        console.log('🔍 请求URL:', url);

        axios.get(url)
            .then(response => {
                console.log('✅ 请求成功:', response.data);
                // 直接使用返回的数组数据
                renderEnrollTable(response.data);
            })
            .catch(error => {
                console.error('❌ 请求失败:', error);
                if (error.response) {
                    console.error('错误状态:', error.response.status);
                    console.error('错误数据:', error.response.data);
                }
                showToast('加载数据出错: ' + (error.message || '网络错误'), 'error');
            });
    }

    // 渲染报名表格
    function renderEnrollTable(enrolls) {
        const tbody = document.getElementById('enrollTableBody');
        tbody.innerHTML = '';

        console.log('🎯 渲染数据，长度:', enrolls ? enrolls.length : 0);

        if (!enrolls || enrolls.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted">暂无报名数据</td></tr>';
            return;
        }

        enrolls.forEach(enroll => {
            console.log('📝 处理报名记录:', enroll);

            const statusInfo = statusMap[enroll.enroll_status] || { text: '未知', class: '' };
            const row = document.createElement('tr');

            row.innerHTML = `
                <td>${enroll.enroll_id || '-'}</td>
                <td>${enroll.activity_id || '-'}</td>
                <td>${enroll.user_id || '-'}</td>
                <td>${formatDate(enroll.enroll_time) || '-'}</td>
                <td><span class="status-badge ${statusInfo.class}">${statusInfo.text}</span></td>
                <td>${enroll.check_user_id || '-'}</td>
                <td>
                    <button class="btn btn-sm btn-outline-primary action-btn" onclick="editEnroll(${enroll.enroll_id})">
                        <i class="bi bi-pencil"></i> 编辑
                    </button>
                    <button class="btn btn-sm btn-outline-danger action-btn" onclick="deleteEnroll(${enroll.enroll_id})">
                        <i class="bi bi-trash"></i> 删除
                    </button>
                </td>
            `;

            tbody.appendChild(row);
        });
    }

    // 格式化日期
    function formatDate(dateString) {
        if (!dateString) return '';
        try {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        } catch (e) {
            console.warn('日期格式错误:', dateString);
            return '无效日期';
        }
    }

    // 编辑报名
    function editEnroll(id) {
        console.log('✏️ 编辑报名:', id);
        axios.get(`${API_BASE}/get/${id}`)
            .then(response => {
                console.log('📋 编辑数据:', response.data);
                const enroll = response.data;

                document.getElementById('enroll_id').value = enroll.enroll_id;
                document.getElementById('activity_id').value = enroll.activity_id;
                document.getElementById('user_id').value = enroll.user_id;
                document.getElementById('enroll_status').value = enroll.enroll_status;
                document.getElementById('check_user_id').value = enroll.check_user_id || '';
                document.getElementById('check_remark').value = enroll.check_remark || '';

                // 显示模态框
                const modal = new bootstrap.Modal(document.getElementById('enrollModal'));
                modal.show();
            })
            .catch(error => {
                console.error('获取报名信息出错:', error);
                showToast('获取报名信息出错', 'error');
            });
    }

    // 保存报名
    function saveEnroll() {
        const enroll = {
            activity_id: parseInt(document.getElementById('activity_id').value) || 0,
            user_id: parseInt(document.getElementById('user_id').value) || 0, // 改为 parseInt
            enroll_status: parseInt(document.getElementById('enroll_status').value) || 0,
            check_user_id: document.getElementById('check_user_id').value ?
                parseInt(document.getElementById('check_user_id').value) : null, // 改为 parseInt
            check_remark: document.getElementById('check_remark').value || null
        };

        console.log('📤 发送数据:', enroll);

        const enrollId = document.getElementById('enroll_id').value;
        const isUpdate = enrollId !== '';

        let url, method;

        if (isUpdate) {
            // 更新操作
            url = `${API_BASE}/update/${enrollId}`;
            method = 'put';
            enroll.enroll_id = parseInt(enrollId);
        } else {
            // 新增操作 - 使用 /add 接口
            url = `${API_BASE}/add`;
            method = 'post';
        }

        axios({
            method: method,
            url: url,
            data: enroll,
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                console.log('✅ 保存成功:', response.data);
                showToast(response.data, 'success'); // 直接使用后端返回的字符串消息
                bootstrap.Modal.getInstance(document.getElementById('enrollModal')).hide();
                loadEnrollData();
            })
            .catch(error => {
                console.error('❌ 保存失败:', error);
                console.error('错误响应:', error.response);
                showToast('保存出错: ' + (error.response?.data || error.message), 'error');
            });
    }

    // 删除报名
    function deleteEnroll(id) {
        if (!confirm('确定要删除这条报名记录吗？')) {
            return;
        }

        console.log('🗑️ 删除报名:', id);

        // 使用 /delete/{id} 接口
        axios.get(`${API_BASE}/delete/${id}`)
            .then(response => {
                console.log('✅ 删除成功:', response.data);
                showToast(response.data, 'success'); // 直接使用后端返回的字符串消息
                loadEnrollData();
            })
            .catch(error => {
                console.error('❌ 删除失败:', error);
                showToast('删除出错', 'error');
            });
    }

    // 显示Toast提示
    function showToast(message, type) {
        const toastEl = document.getElementById('toast');
        const toastMessageEl = document.getElementById('toastMessage');

        toastMessageEl.textContent = message;
        toastEl.classList.remove('text-bg-success', 'text-bg-danger');

        if (type === 'success') {
            toastEl.classList.add('text-bg-success');
        } else {
            toastEl.classList.add('text-bg-danger');
        }

        const toast = new bootstrap.Toast(toastEl);
        toast.show();

        console.log('💬 Toast消息:', message);
    }

    // 清空表单
    document.getElementById('enrollModal').addEventListener('hidden.bs.modal', function () {
        document.getElementById('enrollForm').reset();
        document.getElementById('enroll_id').value = '';
        console.log('🧹 表单已清空');
    });
</script>
</body>
</html>
